package work.chenxr.rabbitmq.sender;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * @Author Chenxr
 * @Date 2023/10/18
 * @Description 队列消息发送者
 */
@Slf4j
@Component
public class MqMessageSender {
    /**
     * 延迟时长
     */
    @Value("${app.rabbitmq.delay.chenxr.time}")
    private Duration delayTime;

    /**
     * 延迟交换机名称
     */
    @Value("${app.rabbitmq.delay.chenxr.exchange}")
    private String chenxrExchange;

    private final RabbitTemplate rabbitTemplate;

    public MqMessageSender(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    /**
     * 发送消息
     *
     * @param msgContent 消息内容
     * @param seconds    秒数，只取第一个有效值
     */
    public void send(String msgContent, Integer... seconds) {
        rabbitTemplate.convertAndSend(chenxrExchange, "delay.chenxr.test", msgContent, message -> {
            MessageProperties messageProperties = message.getMessageProperties();

            // 设置消息的延迟投递时间（具体延迟多久处理可以自定义）
            int millis = (int) delayTime.toMillis();
            if (ObjectUtils.isNotEmpty(seconds) && seconds[0] > 0) {
                millis = seconds[0] * 1000;
            }

            messageProperties.setDelay(millis);
            return message;
        });
        log.info("消息[{}]投递到MQ", msgContent);
    }
}
